const { DefinePlugin } = require('webpack');
const path = require('path');

// 引入插件
const AutoImport = require('unplugin-auto-import/webpack').default;
const Components = require('unplugin-vue-components/webpack').default;
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = {
  mode: 'development',
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true,
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
    extensions: ['.js', '.vue'],
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
  plugins: [
    new VueLoaderPlugin(),
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      imports: [
        // 自动引入 Vue 和 Element Plus 图标的命名空间
        'vue',
      ],
    }),
    Components({
      resolvers: [
        ElementPlusResolver(),
        // 自动引入 Element Plus 图标
        (name) => {
          if (name.startsWith('ElIcon')) {
            return {
              name: name.slice(2),
              from: '@element-plus/icons-vue',
            };
          }
        },
      ],
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: 'Vue 3 Webpack Scaffold',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  devServer: {
    static: './dist',
    hot: true,
    port: 8080,
    open: true,
  },
};
